package com.application.module.withdraw;

import com.application.validate.ApiValidator;
import com.jfinal.core.Controller;
import com.platform.interceptor.AuthInterceptor;
import com.platform.mvc.user.User;

import java.math.BigDecimal;
import java.util.List;

public class WithdrawValidator extends ApiValidator {
	@Override
	protected void validate(Controller c) {
		String key = getActionKey();
        User user = AuthInterceptor.getCurrentUser(c.getRequest(), c.getResponse(), true);

        if (key.equals("/api/withdraw/save")){
		    valiSave(c, user);
		    valiMoney(c, user.getId());
		} else if(key.equalsIgnoreCase("/admin-api/withdraw/update")) {
            valiState(c);
        }

	}

    private void valiState(Controller c) {
        Withdraw wd = Withdraw.dao.findById(c.getPara("id"));
        if(wd != null && wd.getReply_time() != null && wd.getStatus() != Withdraw.STATUS_APPLY) {
            addError("msg", "请勿重复处理");
        }
    }

    private void valiSave(Controller c, User user) {
        List<Withdraw> list = Withdraw.dao.findWaitList(user.getId());
        if(list.size() >0) {
            addError("msg", "已有申请待处理");
        }
	}

    /*
    提现金额校验
     */
	private void valiMoney(Controller c, Integer userId) {
        User user = User.dao.findById(userId);
        BigDecimal dec = user.getBigDecimal("money").add(user.getBigDecimal("gift"));
        String applyMoney = c.getPara("apply_money");
        try {
            if (new BigDecimal(applyMoney).compareTo(dec) >0) {
                addError("msg", "提现金额超出余额");
            }
        } catch (Exception e) {
            addError("msg", "参数错误");
        }
    }
}
